#!/usr/bin/env python
# -*- coding: utf-8 -*-


"""
This is a very humble attempt of producing text for long forms.
Anyway, they have to be heavily edited.

http://code.google.com/p/webpyte/wiki/FormettoFramework
Author: Nando Florestan
License: LGPL
"""

# TODO: Update this module for SQLAlchemy 0.5

from sqlalchemy import DateTime

maxsize = 60

preamble="""<form action="${action}" method="post" class="tableform" id="TheForm">
  <table>"""
after="""  </table>
  ${f.Button(id="btnSend", value="Enviar", action=action)} &nbsp;
  ${f.Button(id="btnRemove", value="Remover", action=removeAction, validate=False, confirmation="Tem certeza de que quer remover?")}
  ${f.scripts(focusfirst=True)}
</form>"""

def get_length(obj, field):
    if hasattr(obj, "c"):
        p = obj.c.get(field)
        # Cannot compare a Column to None with the == operator.
        # This returns a sqlalchemy.sql._BooleanExpression object.
        # Therefore I use the 'is' operator:
        if p is None: p = obj.c.get("_" + field)
        t = p.type
        if isinstance(t, DateTime):
            return 19
        elif  hasattr(t, "length"):
            return t.length
        else:
            return None
    else:
        return None


def desunderline(t):
    return t[1:] if t.startswith("_") else t


def generate_form_for(cls, maxsize=maxsize):
    """Given an ORM class, generates some text for you to start making a
    Formetto form. Nothing will be totally right - but less typing for you.
    
    Usage (in ipython):
        def gen(cls):
            import webpyte.formetto_gen as g
            reload(g)
            print g.generate_form_for(cls)
        gen(Some_ORM_Class)
    """
    exclude = ["id", "created", "changed"]
    #all = [a for a in cls._class_state.attrs \
    #       if not a.startswith("_") and not a in exclude]
    all = [desunderline(a) for a in cls.c.keys() if not a in exclude]
    foreigns = [a for a in all if a.endswith("_id")]
    selects = [a[:-3] for a in foreigns]
    # fields = all - foreigns
    fields = [a for a in all if not a in foreigns]
    # texts = fields - selects
    texts = [a for a in fields if not a in selects]
    lines = [preamble]
    for f in selects:
        s = '    ${f.Select(id="%s", label=u"%s", options = [(t.id, t.display_name, t in SOME_LIST) for t in SOME_LIST])}' % (f, f)
        lines.append(s)
    for f in texts:
        # fi = cls._class_state.attrs[f]
        le = get_length(cls, f)
        #print f, le
        tag = "Text" if le else "TextArea"
        s = '    ${f.%s(id="%s", label=u"%s"' % (tag, f, f)
        if le is not None and le > maxsize:
            s += ', size=' + str(maxsize)
        lines.append(s + ')}')
    lines.append(after)
    return "\n".join(lines)
